import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

/**
 * Created by L.jp
 * Description:
 * User: 86189
 * Date: 2021-12-07
 * Time: 15:36
 */
class node{
    int val=0;
    node left=null;
    node right=null;
}
public class Main {
    public static void createTree(Scanner scanner,node[] arr,int row){
        for(int i=1;i<=row;i++){
            int left=scanner.nextInt();
            int right=scanner.nextInt();
            int val=scanner.nextInt();
            if(left!=0){
                arr[i].left=arr[left];
            }
            if(right!=0){
                arr[i].right=arr[right];
            }
            arr[i].val=val;
        }

    }
    public static  node merge(node root1,node root2){
        //递归合并，先合并左边再合并右边
        if(root1!=null && root2!=null){
            root1.left=merge(root1.left,root2.left);//更新左孩子
            root1.right=merge(root1.right,root2.right);//更新右孩子
            root1.val= root1.val+root2.val;//更新值
            return root1;//返回新生成节点的位置
        }
        return root1==null ? root2:root1;//其中一个为空时直接返回另一个

    }
    public static void bfs(node root){
        Queue<node> queue=new LinkedList<>();
        if(root!=null){
            queue.offer(root);
        }
        while(!queue.isEmpty()){
            node cur=queue.poll();
            System.out.print(cur.val+" ");
            if(cur.left!=null){
                queue.offer(cur.left);
            }
            if(cur.right!=null){
                queue.offer(cur.right);
            }
        }
        System.out.println();
    }
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        int n=scanner.nextInt();
        int m=scanner.nextInt();
        node[] arr1=new node[n+1];//数组存储左右孩子编号以及该节点的值
        node[] arr2=new node[m+1];
        for(int i=0;i<=n;i++){
            arr1[i]=new node();//一行表示一个节点
        }
        for(int i=0;i<=m;i++){
            arr2[i]=new node();
        }
        createTree(scanner,arr1,n);
        createTree(scanner,arr2,m);
        node root1=null;
        node root2=null;
        if(arr1.length>1){
            root1=arr1[1];
        }
        if(arr2.length>1){
            root2=arr2[1];
        }
        node root=merge(root1,root2);
        bfs(root);
    }
}
